<!-- filename: frontend/src/components/AuthModal/AuthModal.vue (内置错误提示最终版) -->
<template>
  <view class="modal-overlay" @click="closeModal">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">{{ isRegisterMode ? '注册' : '登录' }}</text>
        <view class="close-btn" @click="closeModal">×</view>
      </view>

      <!-- 【新增】内置错误提示栏 -->
      <view v-if="errorMessage" class="error-banner">
        {{ errorMessage }}
      </view>

      <view class="modal-body">
        <!-- 用户名输入 -->
        <view class="input-wrapper">
          <input 
            class="input-field" 
            v-model="username" 
            placeholder="请输入用户名" 
            @blur="isRegisterMode && checkUsernameAvailability()"
          />
          <view v-if="isRegisterMode && usernameStatus.message" :class="['validation-message', usernameStatus.type]">
            {{ usernameStatus.message }}
          </view>
        </view>

        <!-- 密码输入 -->
        <view class="password-wrapper">
          <input
            class="input-field"
            v-model="password"
            :type="isPasswordVisible ? 'text' : 'password'"
            placeholder="请输入密码"
            @focus="isRegisterMode && (usernameStatus.message = '')"
          />
          <view class="eye-icon" @click="isPasswordVisible = !isPasswordVisible">
            <svg v-if="isPasswordVisible" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>
            <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/></svg>
          </view>
        </view>
        
        <view v-if="isRegisterMode" class="tos-notice">
          注册即代表您同意，<br>不上传与48系偶像无关的内容，且评论不攻击他人。
        </view>
        
        <button class="submit-btn" @click="handleSubmit">{{ isRegisterMode ? '注册' : '登录' }}</button>
      </view>

      <view class="modal-footer">
        <text class="switch-mode" @click="switchMode">
          {{ isRegisterMode ? '已有账号？去登录' : '没有账号？去注册' }}
        </text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { useAuthStore } from '@/store/auth';

const emit = defineEmits(['close']);
const authStore = useAuthStore();

const isRegisterMode = ref(false);
const username = ref('');
const password = ref('');
const isPasswordVisible = ref(false);
const errorMessage = ref(''); // 【新增】用于在 Banner 中显示错误信息的状态

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

const usernameStatus = reactive({
  type: '',
  message: '',
  isChecking: false,
});
let debounceTimer = null;

const switchMode = () => {
  isRegisterMode.value = !isRegisterMode.value;
  username.value = '';
  password.value = '';
  usernameStatus.message = '';
  usernameStatus.type = '';
  errorMessage.value = ''; // 切换模式时清空错误信息
};

const checkUsernameAvailability = () => {
  if (!username.value) { // 移除长度限制
    usernameStatus.message = '';
    return;
  }
  usernameStatus.isChecking = true;
  usernameStatus.message = '正在检查...';
  usernameStatus.type = '';

  uni.request({
    url: `${API_BASE_URL}/api/users/check-username`,
    method: 'POST',
    data: { username: username.value },
    success: (res) => {
      if (res.data.exists) {
        usernameStatus.type = 'error';
        usernameStatus.message = '该用户名已被占用';
      } else {
        usernameStatus.type = 'success';
        usernameStatus.message = '该用户名可用';
      }
    },
    fail: () => {
      usernameStatus.message = '';
    },
    complete: () => {
      usernameStatus.isChecking = false;
    }
  });
};

const handleSubmit = async () => {
  errorMessage.value = ''; // 每次提交前清空旧的错误信息

  if (!username.value || !password.value) {
    errorMessage.value = '用户名和密码不能为空';
    return;
  }
  if (isRegisterMode.value && password.value.length < 6) {
    errorMessage.value = '密码长度不能少于6位';
    return;
  }
  if (isRegisterMode.value && usernameStatus.type === 'error') {
    errorMessage.value = usernameStatus.message;
    return;
  }

  const url = isRegisterMode.value ? `${API_BASE_URL}/api/register` : `${API_BASE_URL}/api/login`;
  
  uni.showLoading({ title: '请稍候...' });

  uni.request({
    url,
    method: 'POST',
    data: { username: username.value, password: password.value },
    success: (res) => {
      if (res.statusCode >= 400) {
        errorMessage.value = res.data.error || (isRegisterMode.value ? '注册失败' : '登录失败');
        return;
      }
      
      authStore.setAuth(res.data.access_token, res.data.refresh_token, res.data.user);
      const successTitle = isRegisterMode.value ? '注册成功！' : '登录成功！';
      uni.showToast({ title: successTitle, icon: 'success' }); // 成功的提示还是用 Toast
      closeModal();
    },
    fail: () => {
      errorMessage.value = '网络请求失败，请检查网络连接';
    },
    complete: () => {
      uni.hideLoading();
    }
  });
};

const closeModal = () => {
  emit('close');
};

watch(username, (newValue) => {
  if (!isRegisterMode.value) return;
  errorMessage.value = ''; // 用户开始输入时，清空提交错误
  clearTimeout(debounceTimer);
  if (newValue) {
    debounceTimer = setTimeout(() => {
      checkUsernameAvailability();
    }, 500);
  } else {
    usernameStatus.message = '';
  }
});

// 【新增】当用户输入密码时，也清空提交错误
watch(password, () => {
  errorMessage.value = '';
});

</script>

<style scoped lang="scss">
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  width: 90%;
  max-width: 400px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  overflow: hidden; /* 配合 error-banner 的圆角 */
}

/* 【新增】错误提示栏样式 */
.error-banner {
  padding: 10px 20px;
  background-color: #f8d7da;
  color: #721c24;
  font-size: 14px;
  text-align: center;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
}

.close-btn {
  font-size: 24px;
  color: #888;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.input-wrapper {
  margin-bottom: 15px;
  position: relative;
}
.input-wrapper .input-field {
  margin-bottom: 0;
}

.validation-message {
  font-size: 12px;
  padding: 3px 0 0 5px;
}
.validation-message.success {
  color: #28a745;
}
.validation-message.error {
  color: #dc3545;
}

.input-field {
  width: 100%;
  height: 44px;
  padding: 0 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  box-sizing: border-box;
}

.password-wrapper {
  position: relative;
  width: 100%;
  margin-bottom: 15px;
}
.password-wrapper .input-field {
  padding-right: 40px;
  margin-bottom: 0;
}
.eye-icon {
  position: absolute;
  top: 50%;
  right: 12px;
  transform: translateY(-50%);
  cursor: pointer;
  color: #888;
}

.tos-notice {
  font-size: 12px;
  color: #888;
  text-align: center;
  margin-bottom: 20px;
  line-height: 1.5;
}

.submit-btn {
  width: 100%;
  height: 44px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
}
.submit-btn::after {
  border: none;
}

.modal-footer {
  padding: 15px 20px;
  text-align: center;
  border-top: 1px solid #eee;
}

.switch-mode {
  font-size: 14px;
  color: #007aff;
  cursor: pointer;
}
</style>